import path from 'path'
import crypto from 'crypto'
import oss from '../utils/aliyunoss.js'
import db from '../db/index.js'
// 文章的接口处理函数
// 处理传入的图片文件
const disposeFile = async (req, res) => {
    // 生成文件名字,先得到上传的文件后缀名
    const ctx = path.extname(req.file.originalname)
    const uniqueId = crypto.randomBytes(16).toString('hex')
    const newName = uniqueId + ctx
    // 将文件上传到阿里云的oss云存储空间
    const result = await oss.upload(newName, req.file.buffer)
    return result
}
export const addArticle = async (req, res) => {
    if (!req.file || req.file.fieldname !== 'cover_img') return res.cc('文章封面是必选参数！')
    // 处理文件
    try {
        const newPath = await disposeFile(req, res)
        // 添加文章
        const artData = {
            ...req.body,
            cover_img: newPath,
            pub_date: new Date(),
            author_id: req.auth.id
        }
        const sqlStr = 'insert into ev_articles set ?'
        db.query(sqlStr, artData, (err, result) => {
            if (err) {
                console.log(err)
                return res.cc('数据库错误')
            }
            if (result.affectedRows !== 1) return res.cc('发布文章失败')
            // 发布成功
            res.to('发布成功')
        })
    } catch (e) {
        res.cc('服务器错误')
    }
}

// 查询文章列表接口
export const getArticle = (req, res) => {
    const sqlStr = 'select * from ev_articles where author_id=? and is_delete=0'
    db.query(sqlStr, req.auth.id, (err, result) => {
        if (err) return res.cc('数据库错误')
        if (result.length === 0) return res.cc('用户未发布文章')
        // 查询成功
        res.to('查询成功', result)
    })
}